﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cmd.Internal;
using System.Collections;

namespace Cmd.TypeConverters
{
    public class ArrayConverter : ITypeConverter
    {
        public Type BaseType
        {
            get;
            private set;
        }

        public ArrayConverter(Type type)
        {
            BaseType = type;
        }

        public object ConvertFromString(string value)
        {
            if (!BaseType.IsArray)
            {
                throw new ArgumentException("T must be an array type");
            }
            if (value == null)
            {
                return null;
            }

            string[] valListStr = (value as string).Split(',');

            List<object> list = new List<object>();

            Type arrayType = BaseType.GetElementType();
            for (int i = 0; i < valListStr.Length; i++)
            {
                object val = valListStr[i].FromString(arrayType);
                list.Add(val);
            }
            Array arr = Array.CreateInstance(arrayType, list.Count);
            for (int i = 0; i < list.Count; i++)
            {
                arr.SetValue(Convert.ChangeType(list[i], arrayType), i);
            }
            return arr;
        }


        public string ConvertToString(object value)
        {
            if (value == null)
            {
                return null;
            }
            if (!BaseType.IsArray)
            {
                throw new ArgumentException("T must be an array type");
            }
            return string.Join(",", (value as Array).Cast<object>().Select(item => item.ToString(BaseType.GetElementType())));
        }
    }
}
